<template>
  <view class="question-item">

    <!-- 题干和语音 -->
    <view class="title-content">
      <view class="title-header">
        <rich-text class="title-text" :nodes="getTitleWithType(index)"></rich-text>
      </view>

    </view>

    <!-- 图片 -->
    <view class="img-box" v-if="data.img">
      <image :src="data.img" mode="aspectFit" @click="$emit('previewImage', data.img)" />
      <view class="preview-btn" @click="$emit('previewImage', data.img)">
        <text class="iconfont icon-fangdajing"></text>
      </view>
    </view>

    <!-- 选项 -->
    <view class="option-list">
      <view 
        class="option-item" 
        :class="getOptionClass(option)"
        v-for="(option, idx) in data.options" 
        :key="idx"
        @click="selectOption(option, idx)"
      >
        <view class="option-content">
          <rich-text class="option-label" :nodes="option.text"></rich-text>
          <view class="option-status">
            <view v-if="showCorrectAnswer && isCorrectOption(option)" class="correct-icon">
              <text class="iconfont icon-zhengque1"></text>
            </view>
            <view v-if="showWrongAnswer && isWrongOption(option)" class="wrong-icon">
              <text class="iconfont icon-cuowu1"></text>
            </view>
          </view>
        </view>
      </view>
    </view>
    <!-- 多选题提交按钮 -->
    <view v-if="isMultipleChoice && !hasAnswered && selectedOptions.length > 0" class="submit-btn-fixed">
      <button class="submit-btn" @click="submitMultipleChoice">
        提交答案
      </button>
    </view>
    <!-- 答案信息 -->
    <view v-if="showUserSelectedAnswer || question_mode === 2" class="user-answer-tip" :class="isAnswerCorrect ? 'correct' : 'wrong'">
      <view class="answer-info">
        <view class="answer-left">
          <text class="user-answer-text">您的选择：{{ data.userAnswer || '/' }}</text>
          <text class="statistics-text" v-if=" mode != 2">全站正确 {{ data.totalRight || '暂无' }} 次</text>
        </view>
        <view class="answer-right">
          <text class="correct-answer" >正确答案：{{ data.answer }}</text>
          <text class="statistics-text" style="color:#f00" v-if="mode != 2">全站错误 {{ data.totalError || '暂无' }} 次</text>
        </view>
      </view>
    </view>

    <!-- 解析（模拟考试不显示） -->
    <view class="analysis-box" v-if="showAnalysis">
      <text class="analysis-title">试题详解</text>
      <view class="analysis-content">{{ data.analysis }}</view>
    </view>
  </view>
</template>

<script>
// 题型元数据（集中管理题目类型的文案、样式类名与颜色）
const QUESTION_TYPE_META = {
  '1': { text: '单选题', class: 'single-choice', bg: '#e3f2fd', color: '#1976d2' },
  '2': { text: '多选题', class: 'multiple-choice', bg: '#f3e5f5', color: '#7b1fa2' },
  '3': { text: '判断题', class: 'judge', bg: '#e8f5e8', color: '#388e3c' }
}
export default {
  name: 'QuestionItem',
  props: {
    data: {
      type: Object,
      default: () => ({})
    },
    question_mode: {
      type: Number,
      default: 1
    },
    display: {
      type: Boolean,
      default: false
    },
         type: {
       type: [String, Number],
       default: '1'
     },
    index: {
      type: Number,
      default: 0
    },

    showAnswer: {
      type: Boolean,
      default: true
    },
    showUserAnswer: {
      type: Boolean,
      default: false
    },
    questionIndex: {
      type: Number,
      default: 0
    },
    mode: {
      type: Number,
      default: 1
    },
   
  },
  data() {
    return {
      selectedOptions: [],
      isCorrect: false
    }
  },
  watch: {
    question_mode: {
      handler(newMode, oldMode) {
        // 首次加载时 oldMode 为 undefined，跳过处理，保留原始数据
        if (oldMode === undefined) return
        
        if (newMode === 2 && oldMode !== 2) {
          // 切换到背题模式时，保存当前状态并清除显示
          this.saveCurrentState()
          this.clearUserAnswer()
        } else if (newMode !== 2 && oldMode === 2) {
          // 从背题模式切换回其他模式时，恢复用户选择
          this.restoreUserAnswer()
        }
      },
      immediate: true
    }
  },
  computed: {
    // ===== 题型与展示计算 =====
    // 题目类型（确保为字符串）
     questionType() {
       return String(this.data.type || this.type || '1')
     },
    // 是否显示正确答案
    showCorrectAnswer() {
      // 背题模式或已答题时显示正确答案
      return this.showAnswer && (this.question_mode === 2 || this.data.userAnswer !== '')
    },
    // 是否显示错误答案（已答题且答错）
    showWrongAnswer() {
      // 背题模式不显示错误答案，只在答题模式且答错时显示
      return this.showAnswer && this.question_mode !== 2 && this.data.userAnswer !== '' && this.data.userAnswer !== this.data.answer
    },
    // 是否已答题
    hasAnswered() {
      return this.data.userAnswer !== ''
    },
    // 是否显示解析
    showAnalysis() {
      // 背题模式或已答题时显示解析
      return this.data.analysis && (this.question_mode === 2 || this.data.userAnswer !== '')
    },
    // 是否显示用户选择的答案
    showUserSelectedAnswer() {
      // 背题模式不显示用户选择，只在答题模式时显示
      return this.showUserAnswer && this.question_mode !== 2 && this.data.userAnswer !== ''
    },
    // 判断答案是否正确（多选忽略顺序）
    isAnswerCorrect() {
      if (!this.data.userAnswer || !this.data.answer) return false
      if (this.isMultipleChoice) {
        return this.areArraysEqualIgnoreOrder(
          this.splitAnswers(this.data.userAnswer),
          this.splitAnswers(this.data.answer)
        )
      }
      return this.data.userAnswer === this.data.answer
    },
    // 是否为多选题
    isMultipleChoice() {
      return this.questionType === '2'
    }
  },
  methods: {
    // ===== 工具方法（答案处理/比较） =====
    // 将以逗号分隔的答案字符串拆分为数组并去除空白
    splitAnswers(str) {
      if (!str) return []
      return String(str)
        .split(',')
        .map(s => String(s).trim())
        .filter(Boolean)
    },
    // 无序数组比较（值相等且数量一致）
    areArraysEqualIgnoreOrder(a, b) {
      if (!Array.isArray(a) || !Array.isArray(b)) return false
      if (a.length !== b.length) return false
      const sa = [...a].sort()
      const sb = [...b].sort()
      return sa.every((v, i) => v === sb[i])
    },

    // ===== 状态保存/恢复 =====
    // 保存当前状态
    saveCurrentState() {
      this.savedUserAnswer = this.data.userAnswer
      this.savedOptionsState = this.data.options.map(opt => ({ ...opt }))
      this.savedSelectedOptions = [...this.selectedOptions]
    },
    
    // 恢复用户答案
    restoreUserAnswer() {
      if (this.savedUserAnswer !== undefined) {
        this.data.userAnswer = this.savedUserAnswer
      }
      if (this.savedOptionsState) {
        this.data.options.forEach((option, index) => {
          if (this.savedOptionsState[index]) {
            option.checked = this.savedOptionsState[index].checked
          }
        })
      }
      if (this.savedSelectedOptions) {
        this.selectedOptions = [...this.savedSelectedOptions]
      }
    },
    
    // 清除用户答案和选项选中状态
    clearUserAnswer() {
      this.data.userAnswer = ''
      this.data.options.forEach(option => {
        option.checked = false
      })
      this.selectedOptions = []
    },
    
    // ===== 交互处理（点击/提交） =====
    selectOption(option, idx) {
      // 背题模式或已答题或显示模式时不允许选择
      if (this.question_mode === 2 || this.hasAnswered || this.display) return
      if (this.questionType === '2') {
        this.handleMultipleChoice(option)
      } else {
        this.handleSingleChoice(option, idx)
      }
    },
    // 单选题
    handleSingleChoice(option, idx) {
      this.data.options.forEach((opt, i) => {
        opt.checked = i === idx
      })
      this.data.userAnswer = option.value
      this.isCorrect = option.value === this.data.answer
      this.$emit('radioClick', {
        userAnswer: option.value,
        options: this.data.options,
        isCorrect: this.isCorrect,
        questionIndex: this.questionIndex
      })

    },
    // 多选题
    handleMultipleChoice(option) {
      option.checked = !option.checked
      this.selectedOptions = this.data.options.filter(opt => opt.checked).map(opt => opt.value)
      // 多选题不立即提交，等待用户点击提交按钮
    },
    // 提交多选题答案
    submitMultipleChoice() {
      if (this.selectedOptions.length === 0) return
      
      this.data.userAnswer = this.selectedOptions.join(',')
      this.isCorrect = this.areArraysEqualIgnoreOrder(
        this.selectedOptions,
        this.splitAnswers(this.data.answer)
      )
      
      this.$emit('radioClick', {
        userAnswer: this.data.userAnswer,
        options: this.data.options,
        isCorrect: this.isCorrect,
        questionIndex: this.questionIndex
      })
    },
    // ===== 题型辅助（统一从元数据读取） =====
    // 获取题目类型文本
    getQuestionTypeText() {
      const meta = QUESTION_TYPE_META[this.questionType] || QUESTION_TYPE_META['1']
      return meta.text
    },
    // 获取题目类型样式类
    getQuestionTypeClass() {
      const meta = QUESTION_TYPE_META[this.questionType] || QUESTION_TYPE_META['1']
      return meta.class
    },
    // 获取选项样式
    getOptionClass(option) {
      const classes = []
      
      // 背题模式：显示正确答案，不显示用户选择
      if (this.question_mode === 2) {
        if (this.isCorrectOption(option)) {
          classes.push('correct')
        }
        classes.push('disabled')
        return classes
      }
      
      // 多选题：立即显示选中状态
      if (this.isMultipleChoice) {
        if (option.checked) {
          classes.push('checked')
        }
        
        // 如果已经提交答案，显示正确/错误状态
        if (this.hasAnswered) {
          const correctAnswers = this.splitAnswers(this.data.answer)
          const userAnswers = this.splitAnswers(this.data.userAnswer)
          
          if (correctAnswers.includes(option.value)) {
            classes.push('correct')
          } else if (userAnswers.includes(option.value)) {
            classes.push('wrong')
          }
        }
      } else {
        // 单选题和判断题：不显示checked状态，只显示对错样式
        
        // 显示对错样式
        if (this.showCorrectAnswer) {
          if (option.value === this.data.answer) {
            classes.push('correct')
          }
        }
        
        if (this.showWrongAnswer && option.value === this.data.userAnswer) {
          if (option.value !== this.data.answer) {
            classes.push('wrong')
          }
        }
      }
      
      if (this.hasAnswered || this.display) classes.push('disabled')
      return classes
    },
     // 判断是否为正确选项
     isCorrectOption(option) {
       if (this.isMultipleChoice) {
         // 多选题：检查选项是否在正确答案中
         const correctAnswers = this.splitAnswers(this.data.answer)
         return correctAnswers.includes(option.value)
       }
       // 单选题和判断题
       return option.value === this.data.answer
     },
         // 判断是否为错误选项（用户选择但错误的）
    isWrongOption(option) {
      // 背题模式不显示错误选项
      if (this.question_mode === 2) return false
      
      if (this.isMultipleChoice) {
        // 多选题：检查选项是否在用户答案中但不在正确答案中
        const correctAnswers = this.splitAnswers(this.data.answer)
        const userAnswers = this.splitAnswers(this.data.userAnswer)
        return userAnswers.includes(option.value) && !correctAnswers.includes(option.value)
      } else {
        // 单选题和判断题：用户选择了但答案错误
        // 使用 userAnswer 来判断，而不是 option.checked
        return this.data.userAnswer === option.value && option.value !== this.data.answer
      }
    },
     // 获取带题目类型的题干文本
     getTitleWithType(index) {
       const typeTag = `<span class="question-type-tag ${this.getQuestionTypeClass()}" style="display: inline-block; padding: 2px 4px; border-radius: 6px; font-size: 10px; background: ${this.getTypeBackgroundColor()}; color: ${this.getTypeTextColor()}; vertical-align: middle;">${this.getQuestionTypeText()}</span>`
       return typeTag + (index + 1) + '.' + this.data.title
     },
      // 获取题目类型背景色
      getTypeBackgroundColor() {
        const meta = QUESTION_TYPE_META[this.questionType] || QUESTION_TYPE_META['1']
        return meta.bg
      },
      // 获取题目类型文字色
      getTypeTextColor() {
        const meta = QUESTION_TYPE_META[this.questionType] || QUESTION_TYPE_META['1']
        return meta.color
      }
  }
}
</script>

<style lang="scss" scoped>
.question-item {
  padding: 20rpx;
  .title-content {
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
         .title-header {
       flex: 1;
      .title-text {
        font-size: 32rpx;
        line-height: 1.6;
        color: #333;
        font-weight: 500;
      }
    }
  }
  .img-box {
    margin: 20rpx 0;
    text-align: center;
    position: relative;
    image {
      width: 100%;
      // max-width: 400rpx;
      border-radius: 10rpx;
    }
    .preview-btn {
      position: absolute;
      bottom: 10rpx;
      right: 10rpx;
      width: 60rpx;
      height: 60rpx;
      background: rgba(0, 0, 0, 0.6);
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      transition: all 0.3s ease;
      
      &:hover {
        background: rgba(0, 0, 0, 0.8);
        transform: scale(1.1);
      }
      
      &:active {
        transform: scale(0.95);
      }
      
      .iconfont {
        color: #fff;
        font-size: 32rpx;
      }
    }
  }
  .option-list {
    .option-item {
      margin-bottom: 15rpx;
      padding: 20rpx;
      background: #f8f9fa;
      border-radius: 15rpx;
      border: 2rpx solid transparent;
      transition: all 0.3s ease;
      &.checked {
        background: #007bff;
        color: #fff;
        border-color: #007bff;
      }
       &.correct {
         background: #007bff;
         color: #fff;
         border-color: #007bff;
       }
       &.wrong {
         background: #dc3545;
         color: #fff;
         border-color: #dc3545;
       }
      &.disabled {
        opacity: 0.7;
        cursor: not-allowed;
      }
      .option-content {
        display: flex;
        align-items: center;
        justify-content: space-between;
        .option-label {
          flex: 1;
          font-size: 28rpx;
          line-height: 1.3;
        }
        .option-status {
          margin-left: 20rpx;
          .correct-icon, .wrong-icon {
            width: 40rpx;
            height: 40rpx;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            .iconfont {
              font-size: 36rpx;
              color: #fff;
            }
          }
          .correct-icon {
            background: #28a745;
          }
          .wrong-icon {
            background: #dc3545;
          }
        }
      }
    }
  }
  .user-answer-tip {
    margin-top: 30rpx;
    padding: 20rpx;
    border-radius: 10rpx;
    text-align: center;
    &.correct {
      background: #d4edda;
      color: #155724;
      border: 1rpx solid #c3e6cb;
    }
    &.wrong {
      background: #ffcdcd;
      color: #856404;
      border: 4rpx solid #ff008d;
    }
         .answer-info {
       display: flex;
       justify-content: space-between;
       align-items: flex-start;
       gap: 20rpx;
       .answer-left, .answer-right {
         flex: 1;
         display: flex;
         flex-direction: column;
         gap: 8rpx;
       }
       .user-answer-text {
         display: block;
         font-size: 30rpx;
         font-weight: bold;
         line-height: 1.4;
       }
       .correct-answer {
         display: block;
         font-size: 28rpx;
         line-height: 1.4;
       }
       .statistics-text {
         display: block;
         font-size: 24rpx;
         color: #666;
         font-weight: 500;
         line-height: 1.3;
       }
     }
  }
  
  
  
  .submit-btn-fixed {
    position: fixed;
    bottom: 30%;
    left: 50%;
    transform: translateX(-50%);
    z-index: 999;
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(10rpx);
    border-radius: 50rpx;
    padding: 10rpx 20rpx;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.15);
    
    .submit-btn {
      background: #007bff;
      color: #fff;
      border: none;
      padding: 0rpx 40rpx;
      border-radius: 40rpx;
      font-size: 32rpx;
      font-weight: bold;
      cursor: pointer;
      transition: all 0.3s ease;
      min-width: 200rpx;
      
      &:hover {
        background: #0056b3;
        transform: scale(1.05);
      }
      &:active {
        transform: scale(0.98);
      }
    }
  }
  .analysis-box {
    margin-top: 30rpx;
    padding: 20rpx;
    background: #f7f7f7;
    border-radius: 10rpx;
    .analysis-title {
      font-weight: 700;
      font-size: 30rpx;
      color: #1D1D1D;
      margin-bottom: 10rpx;
      display: block;
    }
    .analysis-content {
      font-size: 28rpx;
      color: #3B3B3B;
    }
  }
}
</style> 